package com.goddess.yeecolor.tools;

import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.goddess.yeecolor.activity.MyAppClient;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 微信支付
 */
public class wxPayActivity {

    public static wxPayActivity wx;

    public static wxPayActivity getIntance(){

        if (wx==null){
            wx=new wxPayActivity();
        }
        return wx;
    }

    public  void pay(String title,String out_trade,int total_fee){

        try {
            Map<Object,Object>map=new HashMap<>();
            map.put("body",title);
            map.put("order_id",out_trade);
            map.put("total_fee",total_fee+"");

            LogUtils.getInstence().info(MyUrl.WXPAy+"?body="+title+"&order_id="+out_trade+"&total_fee="+total_fee);
            OkttpUtils.getIntence().OkttpPost(MyUrl.WXPAy,map,handler,1);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    private String jsonString;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                requestPay(object);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };
    /**
     * 请求微信的支付界面
     */
    private void requestPay(JSONObject json){
        IWXAPI iwxapi= WXAPIFactory.createWXAPI(MyAppClient.getInstance(),Constans.App_ID);
        if (!iwxapi.isWXAppInstalled()){
            Toast.makeText(MyAppClient.getInstance(),"没有安装微信",Toast.LENGTH_SHORT).show();
            return;
        }
        iwxapi.registerApp(Constans.App_ID);
        PayReq resp=new PayReq();
        try {
            JSONObject data=json.getJSONObject("data");
            resp.appId=data.getString("appid");
            resp.partnerId=data.getString("mch_id");

            resp.prepayId=data.getString("prepay_id");
            resp.packageValue="Sign=WXPay";
            resp.nonceStr=data.getString("nonce_str");
            resp.timeStamp=genTimeStamp()+"";


            SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
            parameters.put("appid", data.getString("appid"));
            parameters.put("partnerid", data.getString("mch_id"));
            parameters.put("prepayid",data.getString("prepay_id"));
            parameters.put("noncestr",data.getString("nonce_str"));
            parameters.put("package","Sign=WXPay");
            parameters.put("timestamp",genTimeStamp()+"");
            String characterEncoding = "UTF-8";
            String sign = createSign(characterEncoding,parameters);//生成签名

            resp.sign=sign;


        }
        catch (Exception e){
            e.printStackTrace();

        }
        iwxapi.sendReq(resp);

    }
    //时间
    private long genTimeStamp() {
        return System.currentTimeMillis()/1000;
    }

    /**
     * 生成签名
     * @param characterEncoding
     * @param parameters
     * @return
     */
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key="+Constans.MCH_API_KEY);
        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return packageSign;
    }


}
